import cgi
import os
import sys

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import fetcher
import gdata  # For gdata.service.RequestError


def GetCGIKey(self):
    key = cgi.escape(self.request.get('key'))
    if not key:
        key = '0Ag6KP9FRyXe1cFlvc2FhUm9iT1BjSTRqcWlsVDlyQkE'
    return key


def GetCustomizationData(key=None):
    try:
        context, annos = fetcher.GetCSEPatternsFromPublicSpreadsheet(
            key, 0.7, ['deflabel'])
    except gdata.service.RequestError, e:
        context = {}
        annos = []
    return (context, annos)


class CustomizationsPage(webapp.RequestHandler):
    def get(self):
        key = GetCGIKey(self)
        context, annos = GetCustomizationData(key=key)
        if context and annos is None:
            m = """"No (properly formatted?) data available for key %s"""
            self.response.out.write(m % key)
            return

        path = os.path.join(os.path.dirname(__file__), 'customizations.xml')
        template_values = {
            'annotations': annos,
            'context': context
            }
        content = template.render(path, template_values)

        self.response.headers['Content-Type'] = "application/xml"
        self.response.out.write(content)


class SearchPage(webapp.RequestHandler):
    def get(self):
        key = GetCGIKey(self)
        path = os.path.join(os.path.dirname(__file__), 'searchbox.html')
        template_values = { 'key': key }
        content = template.render(path, template_values)
        self.response.out.write(content)


application = webapp.WSGIApplication(
    [('/', CustomizationsPage),
     ('/customizations', CustomizationsPage),
     ('/search', SearchPage)
     ],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
